<?php
namespace common\wechat;

use Yii;
use yii\log\Logger;

use common\wechat\interfaces\Ireply; 
use common\tools\YWeChatPrint;
use common\models\User;

class ReplyUnsubscribeEvent implements Ireply
{
    protected $_postObject;
    protected $_fromUserName;
    protected $_toUserName;
    protected $_event;
    protected $_time;
    
    public function __construct($postObj) {
        // 获取参数   
        $this->_postObject = $postObj;  
        $this->_time = time();      
        $this->_fromUserName = $this->_postObject->FromUserName;      
        $this->_toUserName =  $this->_postObject->ToUserName;   
        $this->_event = $this->_postObject->Event;      
        $this->eventHandle();
    }
    private function eventHandle(){
        $user = User::findByOpenid($this->_fromUserName);
        if($user){
            $user->subscribe   = 0;//标记为取消关注
            if(!$user->save()){
                Yii::getLogger()->log("标记微信用户{$user->username}取消关注失败", Logger::LEVEL_INFO);
            }
        }else{
            Yii::getLogger()->log("微信用户(openid:{$this->_fromUserName}不存在)", Logger::LEVEL_INFO);
        }
        
    }  
    public function createReMsg(){
    	$content = "";
    	switch ($this->_event)
    	{          
            case "unsubscribe": //取消关注事件
                $content = "再见，欢迎再次关注！";
                //需要回显
    	        $result = YWeChatPrint::print_text($this->_fromUserName,$this->_toUserName,$content);                           
                break;               					
            default:
                $content = "你好！";
                //需要回显
                $result = YWeChatPrint::print_text($this->_fromUserName,$this->_toUserName,$content);
                break;
        }
    	return $result;
    }                                                                      
}

